package com.zhangfb95.crosschain.server.service.impl;

import com.zhangfb95.crosschain.infra.exception.BusinessException;
import com.zhangfb95.crosschain.server.infra.model.mapper.entity.ChainAccount;
import com.zhangfb95.crosschain.server.service.SignHandler;
import com.zhangfb95.crosschain.server.service.SignService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhangfubing
 * @since 2023/12/1
 */
@Service
public class SignServiceImpl implements SignService {

    @Autowired(required = false)
    private List<SignHandler> signHandlers;
    private Map<String, SignHandler> signHandlerMap;

    @PostConstruct
    public void init() {
        if (signHandlers != null) {
            signHandlerMap = signHandlers.stream().collect(Collectors.toMap(SignHandler::supportedAlgType, o -> o));
        }
    }

    @Override
    public byte[] sign(ChainAccount chainAccount, byte[] bytes) {
        SignHandler signHandler = signHandlerMap.get(chainAccount.getAlgType());
        if (signHandler == null) {
            throw new BusinessException("signHandler not find, algType=" + chainAccount.getAlgType());
        }
        return signHandler.sign(chainAccount, bytes);
    }
}
